<!DOCTYPE html>
<html lang="ch-CN">
<head>
    <meta charset="UTF-8">
    <title>事件的绑定</title>
</head>
<style>
    body {
        margin: 0;
        padding: 0;
    }

    #container {
        width: 100%;
        height: 500px;
        background-color: wheat;
        font-size: 30px;
        /*文本透明*/
        /*text-decoration: none;*/
        font-family: "华文楷体";
        position: relative;
    }

    #box1 {
        width: 100px;
        height: 100px;
        background-color: #b3b1af;
        border: solid 1px black;
        text-align: center;
    }

    #box2 {
        width: 100px;
        height: 100px;
        background-color: #b3b1af;
        border: solid 1px black;
        position: absolute;
        margin-left: 45%;
        margin-top: 15%;
        text-align: center;
    }

</style>
<body>
<div id="container">
    <div id="box1">box1</div>
    <div id="box2">box2</div>
</div>

</body>
<script>
    var box1 = document.getElementById("box1")
    var box2 = document.getElementById("box2")
    var container = document.getElementById("container")

    function box_move(box) {
        let count =1
        box.onmousedown = function (event) {
            // 鼠标每次点击box时都向上1个单位——使移动的这个div永远覆盖在另一个div上
            box.style.zIndex = count
            count++
            // 计算指针在box中的位置
            let box_X = event.offsetX
            let box_Y = event.offsetY
            container.onmousemove = function (event) {
                if (event.pageY-box_Y<=-5||event.pageX-box_X<=-5||
                    //container盒子高度-box1盒子高度<=指针离顶端的高度-指针在container盒子的高度(即box不出下边界)
                    container.clientHeight - box1.clientHeight <= event.pageY - box_Y||
                    //container盒子宽度-box1盒子宽度<=指针离左端的宽度-指针在container盒子的宽度(即box不出右边界)
                    container.clientWidth - box1.clientWidth <= event.pageX - box_X) {
                    alert("请不要越界！！")
                    // 重新加载页面
                    location.reload();
                }
                box.style.position = "absolute"
                // 如果CSS中写了margin这里必须清除，不然box移动后系统会默认加上CSS中的margin
                box.style.marginTop = "0"
                box.style.marginLeft = "0"
                box.style.top = event.pageY - box_Y + "px"
                box.style.left = event.pageX - box_X + "px"
            }
            container.onmouseup = function () {
                container.onmousemove = null
                container.onmouseup = null
            }
            //当拖动内容或者ctrl-A时  功能会出现异常，通过return false取消默认行为
            return false
        }
    }

    box_move(box1)
    box_move(box2)
</script>
</html>